import { userApi } from '/api/user'
import { isLogin } from '/store/mutations'
import { checkAuth, getUser } from '/store/actions'
import { $event } from '/utils'
Page({
  data: {
    navData: [
      { name: '推荐', page: 0, isLastpage: false },
      { name: '活跃', page: 0, isLastpage: false },
      { name: '同城', page: 0, isLastpage: false },
    ],
    cur: 0,
    list: [] as any[],
    follower: false,
    scrollClass: false,
    user: {},
  },
  onLoad() {
    if (!isLogin()) {
      checkAuth()
    }
    $event.on('after:login', this, () => {
      this.getUserList()
    })
    this.getUserList()
  },
  async onPullDownRefresh() {
    await this.getUserList()
    wx.stopPullDownRefresh()
  },
  onReachBottom() {
    if (this.data.navData[this.data.cur].isLastpage) {
      wx.showToast({
        title: '已没有更多',
        icon: 'none',
        duration: 1000,
      })
    } else {
      this.getUserList(true)
    }
  },
  onPageScroll() {
    this.fixedTitle()
  },
  /** 判断是否滚动到了导航 */
  fixedTitle() {
    const query = wx.createSelectorQuery().in(this)
    query.select('#header').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec((res: any) => {
      this.setData({
        scrollClass: res[0] && res[0].bottom < 0,
      })
    })
  },
  chooseTab(e: WechatMiniprogram.BaseEvent) {
    const index = e.currentTarget.dataset.index
    if (index === this.data.cur) return
    this.setData({
      cur: index,
    })
    if (this.data.list[this.data.cur]) return
    this.getUserList()
  },
  async getUserList(isLoadMore = false) {
    if (isLoadMore) {
      wx.showLoading({
        title: '加载中',
      })
    }

    const index = this.data.cur
    const offset = isLoadMore ? this.data.list[index].length : 0
    const list =
      index === 0
        ? await userApi.getRecommendUser({ offset })
        : index === 1
          ? await userApi.getActiveUser({ active: 1, offset })
          : await userApi.getLocationUser({ offset })
    this.setData({
      [`list[${index}]`]:
        isLoadMore && this.data.list[index] ? [...this.data.list[index], ...list] : list,
      [`navData[${index}].isLastpage`]: list.length < 15,
      [`navData[${index}].page`]: offset,
    })
    if (isLogin()) {
      this.setData({
        user: getUser(),
      })
    }
    wx.hideLoading()
  },
  async follower(e: WechatMiniprogram.BaseEvent) {
    if (this.data.follower) return
    this.setData({
      follower: true,
    })
    const index = e.currentTarget.dataset.index
    const cur = this.data.cur
    const list = this.data.list[cur]
    list[index].has_follower
      ? await userApi.unFollowUser(list[index].id)
      : await userApi.followUser(list[index].id)
    this.setData({
      [`list[${cur}][${index}].has_follower`]: !list[index].has_follower,
      follower: false,
    })
    wx.showToast({
      title: list[index].has_follower ? '关注成功' : '已取消关注',
      icon: 'none',
      duration: 1000,
    })
  },
})
